// pages/publish/index.js
// import res from 'express/lib/response'
import moment from 'moment'
import {request} from '../../request/index.js'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        title:0,
        phone:'',
        detail:'',
        price:'',
        location:'',
        prePrice:'',
        coverPic:'',
        fileList: [],
        imgList:[],
        categoryList:[],
        categoryNameList:[],
        category: 0,
        tempList:[],
        openid:'',
        pictureOne:'',
        pictureTwo:'',
        pictureThree:'',
        pictureFour:'',
        pictureFive:'',
        pictureSix:'',
        userInfo:{},
        publishInfo:{},
        goodsId:''
      

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      const openid = wx.getStorageSync("openid");
      const userInfo = wx.getStorageSync("userInfo");
      this.setData({
        openid,
        userInfo
      })
        this.getCategoryList()
       
    },


    //获取详细地址
    chooseLocation(){
        wx.chooseLocation({
            success:res=>{
              this.setData({
                  location:res.address
              })
            }
        })
    },

  //图片预览
    previewImg: function(event) {
      
        var src = event.detail.url; 
        var imgList = []; 
        const {
          fileList = []
        } = this.data
        fileList.forEach((item, index, fileList) => {
          imgList.push(item.url);
        })
        //图片预览
        wx.previewImage({
          current: src, // 当前显示图片的http链接
          urls: imgList // 需要预览的图片http链接列表
          
        })
      },
    
    
      //删除图片
      deleteToCloud: function(event) {
        
        let fileID = event.detail.file.url
        let index = event.detail.index
        let fileList_new = this.data.fileList
        let imgList_new = this.data.imgList
        wx.showLoading({
          title: '正在删除',
        });
        wx.cloud.deleteFile({
          fileList: [fileID],
          success: res => {
            console.log("图片删除成功", res)
            fileList_new.splice(index, 1);
            imgList_new.splice(index, 1);
            wx.hideLoading();
            wx.showToast({
              icon: 'success',
              title: '删除成功'
            })
            this.setData({
              fileList: fileList_new,
              imgList: imgList_new
            })
          },
          fail: err => {
            wx.hideLoading();
            wx.showToast({
              icon: 'none',
              title: '删除失败'
            })
            console.log(err)
          }
        })
      },
    
    
    //上传图片到云存储
      uploadToCloud: function(event) {
      
        const {
          fileList = []
        } = this.data
       const {
         imgList = []
       } = this.data
    
        const {
          file
        } = event.detail
       
        file.forEach((item, index, file) => {
          
          wx.showLoading({
            title: '正在提交',
          });
          wx.cloud.uploadFile({
            cloudPath: `goods/${(new Date()).getTime() + Math.floor(9 * Math.random())}` + ".jpg", // 上传至云端的路径
            filePath: item.path, // 小程序临时文件路径
            success: res => {
              // 返回文件 ID
              fileList.push({
                url: res.fileID
              });
              imgList.push(res.fileID)
                
              // const {imgList} = this.data
              // fileList.forEach(v=>{
              //   imgList.push(v.url)
              // })
              // console.log(imgList)
              
              this.setData({
                fileList,
               imgList
              });
             
              wx.hideLoading();
            },
            fail: function() {
              wx.hideLoading();
              console.error
            }
          })
        });
      },
    
  
    // 选择分类
    bindPickerChange: function(e) {
        // console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
          category: Number(e.detail.value)
        })
      },

getUrl(){
  console.log(this.data.imgList)
  wx.cloud.getTempFileURL({
    fileList: this.data.imgList,
    success: res => {
      // get temp file URL
      console.log(res.fileList)
    },
    fail: err => {
      // handle error
    }
  })
},


      publich(event){
       
        if(this.data.fileList.length == 0 ){
          wx.showToast({
            title: '信息未填写完整',
            icon: 'error',
            duration: 10000
          })
          return
        }
        
        const fileListString = JSON.stringify(this.data.fileList)
        
    
          //从云存储获取封面
          wx.cloud.getTempFileURL({
            fileList: this.data.imgList,
         
            success: res => {
              // get temp file URL
              console.log(res.fileList)
              this.setData({
                coverPic:res.fileList[0].tempFileURL,
               tempList:res.fileList
            })
            wx.showLoading({
              title: '正在发布',
             
              duration: 1000
            });
           
        // request({
        //         url: 'http://127.0.0.1:6060/api/addGoods',
        //         header: {"Content-Type": "application/json; charset=utf-8"},
        //         method: 'post',
        //         data:{
        //             fileListString,
        //             avatarUrl:this.data.userInfo.avatarUrl,
        //             coverPic:this.data.coverPic,
        //             userId:this.data.openid,
        //             userName:this.data.userInfo.nickName,
        //             location:this.data.location,
        //             phone: event.detail.value.phone,
        //             price: event.detail.value.price,
        //             detail: event.detail.value.detail,
        //             prePrice: event.detail.value.prePrice,
        //             title: event.detail.value.title,
        //             category:this.data.categoryNameList[this.data.category],
        //             time:moment().format('YY-MM-DD HH:mm:ss'),
        //             tempList:this.data.tempList
        //         }
        //   }).then(value=>{
        //     console.log(value)
        //     const goodsId = result.data.message
        //     wx.navigateTo({
        //       url: '/pages/publishSuceess/publishSuccess?goodsId='+goodsId,
        //     });
        //   })
          // console.log(res.data)
          // const goodsId = result.data.message
          //         wx.navigateTo({
          //           url: '/pages/publishSuceess/publishSuccess?goodsId='+goodsId,
          //         });
          

            wx.request({
              url: 'http://127.0.0.1:6060/api/addGoods',
              header: {"Content-Type": "application/json; charset=utf-8"},
              method: 'post',
              data:{
                  fileListString,
                  avatarUrl:this.data.userInfo.avatarUrl,
                  coverPic:this.data.coverPic,
                  userId:this.data.openid,
                  userName:this.data.userInfo.nickName,
                  location:this.data.location,
                  phone: event.detail.value.phone,
                  price: event.detail.value.price,
                  detail: event.detail.value.detail,
                  prePrice: event.detail.value.prePrice,
                  title: event.detail.value.title,
                  category:this.data.categoryNameList[this.data.category],
                  time:moment().format('YY-MM-DD HH:mm:ss'),
                  tempList:this.data.tempList
              },
              success: (result) => {
                  console.log(result.data)
                // wx.hideLoading();
               const goodsId = result.data.message
                  wx.navigateTo({
                    url: '/pages/publishSuceess/publishSuccess?goodsId='+goodsId,
                  });
               },
               fail: err => {
                wx.hideLoading();
                wx.showToast({
                  title: '发布失败',
                  duration: 1000,
                  icon:'error'
                })
              }
          })
            },
            
          }) 
    },

   



    // 获取分类
    getCategoryList(){
        wx.request({
            url: 'http://127.0.0.1:6060/api/getCategoryList',
            header: {'content-type':'application/json'},
            method: 'GET',
            dataType: 'json',
            success: (result) => {
                const categoryList = result.data.data
                const categoryNameList = ['其他']
                categoryList.forEach(v => {
                    categoryNameList.push(v.categoryName)
                });
                // console.log(categoryNameList)
                this.setData({
                    categoryList,
                    categoryNameList
                })
            },
            
        });
    }
   
})



